/*
 */
package logistics.auth;

import aptech.eproject.logictics.dao.kien.LoginServiceRemote;
import aptech.logictics.Util;
import java.security.acl.Group;
import java.util.Map;
import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.login.LoginException;
import org.jboss.security.SimpleGroup;
import org.jboss.security.SimplePrincipal;
import org.jboss.security.auth.spi.UsernamePasswordLoginModule;

/**
 *
 * @author Kien Nguyen <solidfoxrock at gmail.com>
 */
public class LoginModule extends UsernamePasswordLoginModule {

    private LoginServiceRemote service;

    public LoginModule() {
    }

    @Override
    public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) {
        super.initialize(subject, callbackHandler, sharedState, options);
        service = Util.lookupLoginService();
    }

    protected String getUsersPassword() throws LoginException {
        String passwd = null;
        passwd = service.getPassword(this.getUsername());
//        System.out.println("[LoginModule] Found password: " + passwd);
        return passwd;
    }

    protected Group[] getRoleSets() throws LoginException {
        String[] roles = null;
        String role = service.getRole(this.getUsername());
//        System.out.println("[LoginModule] Found role: " + role);

        roles = new String[]{role};
        Group[] groups = {new SimpleGroup("Roles")};
        for (int r = 0; r < roles.length; r++) {
            SimplePrincipal principle = new SimplePrincipal(roles[r]);
            groups[0].addMember(principle);
        }
        return groups;
    }
}
